package com.tengju.user.infrastructure.schedule;

import com.tengju.user.application.archives.StarSignService;
import com.tengju.user.domain.model.sign.StarSignInfo;
import com.tengju.user.domain.model.sign.StarSignInfoRepository;
import com.tengju.user.domain.model.user.ManageUser;
import com.tengju.user.domain.model.user.Staff;
import com.tengju.user.domain.shared.DateUtil;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class StarInviteExpireJob {

    @Autowired
    StarSignService starSignService;

    @Autowired
    StarSignInfoRepository starSignInfoRepository;

    private int LIMIT_NUM = 1000;

    private final String jobName = "星级签约邀请失效任务";

    private final String jobKey = "starInviteExpireJob";


    @XxlJob("starInviteExpireJob")
    public ReturnT<String> execute(String params) {
        XxlJobLogger.log("{} 开始, param:{}", jobName, params);
        log.info("{} 开始, param:{}", jobName, params);
        long start = System.currentTimeMillis();
        try {
            LocalDateTime expireDate = LocalDateTime.now();
            if (!StringUtils.isBlank(params)) {
                expireDate = DateUtil.dateToLocalDateTime(DateUtil.parseStringToDate(DateUtil.DATE_DAY_FORMAT, params));
            }
            expireDate.withHour(0).withMinute(0).withSecond(0).withNano(0);
            Integer count = starSignInfoRepository.countExpireRecord(expireDate);
            int index = 0;
            while (index <= count) {
                List<StarSignInfo> starSignInfoList = starSignInfoRepository.listExpireRecord(expireDate, LIMIT_NUM);
                if (CollectionUtils.isEmpty(starSignInfoList)) {
                    break;
                }
                for (StarSignInfo starSignInfo : starSignInfoList) {
                    try {
                        starSignService.doStopSign(starSignInfo, Staff.getAdminStaff());
                    } catch (Exception e) {
                        log.error("星级邀约失效失败,idCode:{}", starSignInfo.getIdCode().getValue(), e);
                    }
                }
                index += LIMIT_NUM;
            }
        } catch (Exception e) {
            log.error("{}, jobError", jobName, e);
            return ReturnT.FAIL;
        }
        XxlJobLogger.log("{}} 结束, param:{}, 耗时为:{}ms", jobName, params, System.currentTimeMillis() - start);
        return ReturnT.SUCCESS;
    }

}
